<template>
    <div class="app-container">
        <div class="filter-container">
                <el-input v-model="listQuery.menuName" placeholder="菜单名称" style="width: 180px;" class="filter-item" @keyup.enter.native="handleFilter" />
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                {{ $t('table.search') }}
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate('root')">
                添加根节点
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate('sub')">
                添加子节点
            </el-button>
        </div>

        <el-table
                :key="tableKey"
                v-loading="listLoading"
                :data="list"
                border
                fit
                row-key="id"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                @current-change="handleCurrentChange"
                highlight-current-row
                style="width: 100%;margin-top:10px"
                @sort-change="sortChange"
        >
                <el-table-column label="编号" prop="id" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.id }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="类型" prop="menuType" sortable="true" align="center" width="100" >
                    <template slot-scope="{row}">
                        <span>{{ row.menuType | dictValueFilter('MENU_TYPE')}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="名称" prop="menuName" sortable="true" align="center" width="120" >
                    <template slot-scope="{row}">
                        <span>{{ row.menuName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="代码" prop="menuCode" sortable="true" align="center" width="120" >
                    <template slot-scope="{row}">
                        <span>{{ row.menuCode }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="描述" prop="menuDescription" sortable="true" align="center" width="180" >
                    <template slot-scope="{row}">
                        <span>{{ row.menuDescription }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="Icon" prop="menuIcon" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.menuIcon }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="级别" prop="menuLevel" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.menuLevel }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="排序" prop="menuSortNo" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.menuSortNo }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="地址" prop="menuUrl" sortable="true" align="center" width="180" >
                    <template slot-scope="{row}">
                        <span>{{ row.menuUrl }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="状态" prop="menuStatus" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.menuStatus | dictValueFilter('BASE_STATUS')}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="是否隐藏" prop="hidden" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.hidden.toString() | dictValueFilter('BOOLEAN_TYPE')}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="是否缓存" prop="cache" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.cache.toString() | dictValueFilter('BOOLEAN_TYPE')}}</span>
                    </template>
                </el-table-column>
            <el-table-column label="操作" align="center" width="300px" class-name="small-padding fixed-width">
                <template slot-scope="{row,$index}">
                    <el-button type="primary" size="mini" @click="handleUpdate(row)">
                        {{ $t('table.edit') }}
                    </el-button>
                    <el-button  size="mini" type="danger" @click="handleDelete(row,$index)">
                        {{ $t('table.delete') }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>


        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @open="openDialog()" @close="closeDialog()">
            <el-form ref="dataForm" :rules="rules" :model="temp"  label-width="120px" style="width: 450px; margin-left:50px;">
                    <el-form-item label="菜单类型" prop="menuType">
                        <base-select :dictType="'MENU_TYPE'" v-model="temp.menuType" class="filter-item" placeholder="Please select">
                        </base-select>
                    </el-form-item>
                    <el-form-item label="父菜单名称" prop="parentMenuName">
                        <el-input v-model="temp.parentMenuName" disabled="true" />
                    </el-form-item>
                    <el-form-item label="菜单名称" prop="menuName">
                        <el-input v-model="temp.menuName" />
                    </el-form-item>
                    <el-form-item label="菜单代码" prop="menuCode">
                        <el-input v-model="temp.menuCode" />
                    </el-form-item>
                    <el-form-item label="菜单描述" prop="menuDescription">
                        <el-input v-model="temp.menuDescription" />
                    </el-form-item>
                    <el-form-item label="菜单Icon" prop="menuIcon">
                        <el-input v-model="temp.menuIcon" />
                    </el-form-item>
                    <el-form-item label="菜单排序" prop="menuSortNo">
                        <el-input v-model="temp.menuSortNo" />
                    </el-form-item>
                    <el-form-item label="菜单地址" prop="menuUrl">
                        <el-input v-model="temp.menuUrl" />
                    </el-form-item>
                    <el-form-item label="菜单状态" prop="menuStatus">
                        <base-select :dictType="'BASE_STATUS'" v-model="temp.menuStatus" class="filter-item" placeholder="Please select">
                        </base-select>
                    </el-form-item>
                    <el-form-item label="是否隐藏" prop="hidden">
                        <base-select :dictType="'BOOLEAN_TYPE'" v-model="temp.hidden" class="filter-item" placeholder="Please select">
                        </base-select>
                    </el-form-item>
                    <el-form-item label="是否缓存" prop="cache">
                        <base-select :dictType="'BOOLEAN_TYPE'"   v-model="temp.cache" class="filter-item" placeholder="Please select">
                        </base-select>
                    </el-form-item>
                    <el-form-item label="页面元素" prop="pageElement" v-if="pageElementShow">
                        <el-checkbox-group v-model="temp.pageElement">
                            <el-checkbox-button v-for="element in elementList" :label="element"  :key="element.elementCode">{{element.elementName}}</el-checkbox-button>
                        </el-checkbox-group>
                    </el-form-item>
            </el-form>
            <el-dialog
                width="30%"
                title="添加页面元素"
                :visible.sync="innerVisible"
                append-to-body>
                <el-form ref="btnForm" :rules="rules" :model="btn"  label-width="120px" style="width: 300px; margin-left:50px;">
                     <el-form-item label="菜单代码" prop="elementCode">
                        <el-input v-model="btn.elementCode" />
                    </el-form-item>
                     <el-form-item label="菜单名称" prop="elementName">
                        <el-input v-model="btn.elementName" />
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="innerVisible = false">
                        {{ $t('table.cancel') }}
                    </el-button>
                    <el-button type="primary" @click="addBtn()">
                        {{ $t('table.confirm') }}
                    </el-button>
                </div>
                </el-dialog>
            <div slot="footer" class="dialog-footer">
                <el-button v-if="pageElementShow" @click="innerVisible = true">
                    添加页面元素
                </el-button>
                <el-button @click="dialogFormVisible = false">
                    {{ $t('table.cancel') }}
                </el-button>
                <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
                    {{ $t('table.confirm') }}
                </el-button>
            </div>
        </el-dialog>



    </div>
</template>

<script>
    import { page , create, update, del,selectOne,menuTree } from '@/api/rbac/Menu'
    import waves from '@/directive/waves' // waves directive
    import { parseTime } from '@/utils'
    import BaseSelect from '@/components/Dict'
    import { MessageBox } from 'element-ui'
    import { dictArray } from '@/utils/dict' // get token from cookie

    export default {
        name: 'menu',
        components: { BaseSelect },
        directives: { waves },
        filters: {
        },
        data() {
            return {
                tableKey: 0,
                list: null,
                total: 0,
                listLoading: true,
                listQuery: {
                    sort: 'id desc',
                            id : '',
                            menuType : null,
                            parentMenuName : null,
                            menuName : null,
                            menuCode : null,
                            menuStatus : null
                },
                temp: {
                    id : '',
                    menuType : '',
                    menuLinkId : '',
                    parentId : '',
                    parentMenuName : '',
                    menuName : '',
                    menuCode : '',
                    menuDescription : '',
                    menuIcon : '',
                    menuLevel : '',
                    menuSortNo : '',
                    menuUrl : '',
                    menuMethod : '',
                    menuStatus : '',
                    createUserid : '',
                    createTime : '',
                    updateUserid : '',
                    updateTime : '',
                    pageElement:[],
                    hidden:'',
                    cache:''
                },
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '编辑',
                    create: '新增'
                },
                rules: {
                },
                downloadLoading: false,
                currentRow: null,
                pageElementShow: false,
                elementList:[],
                innerVisible: false,
                btn:{
                    elementCode:'',
                    elementName:''
                }
            }
        },
        created() {
            this.getList()
        },
        methods: {
            getList() {
                this.listLoading = true
                menuTree().then(response => {
                    this.list = response.data
                    this.listLoading = false
            })
            },
            handleFilter() {
                this.getQueryList()
            },
            getQueryList(){
                if(this.listQuery.menuName ==''){
                    this.getList()
                }else{
                    if( this.list ==null || this.list.length==0){
                        this.getList()
                    }
                    var array = []
                    this.list.forEach(element => {
                        if(element.menuName==this.listQuery.menuName){
                            array.push(element)
                        }else {
                            element.children.forEach(menu =>{
                                if(menu.menuName==this.listQuery.menuName){
                                    array.push(element)
                                }
                            })
                        }
                    });
                    this.list = array
                }
            },
            handleModifyStatus(row, status) {
                this.$message({
                    message: '操作成功',
                    type: 'success'
                })
                row.status = status
            },
            sortChange(data) {
                const { prop, order } = data
                //   if (prop === 'id') {
                this.sortBy(prop,order)
                //   }
            },
            sortBy(prop,order) {
                if (order === 'ascending') {
                    this.listQuery.sort = prop + ' asc'
                } else {
                    this.listQuery.sort = prop + ' desc'
                }
                this.handleFilter()
            },
            resetTemp() {
                this.temp = {
                            id : '',
                            menuType : '',
                            menuLinkId : '',
                            parentId : '',
                            parentMenuName : '',
                            menuName : '',
                            menuCode : '',
                            menuDescription : '',
                            menuIcon : '',
                            menuLevel : '',
                            menuSortNo : '',
                            menuUrl : '',
                            menuMethod : '',
                            menuStatus : '',
                            createUserid : '',
                            createTime : '',
                            updateUserid : '',
                            updateTime : '',
                            pageElement:[],
                            hidden:'',
                            cache:''
                }
            },
            handleCreate(type) {
                this.resetTemp()
                if(type =='root'){
                    this.temp.parentId = 0;
                }else if(type =='sub'){
                    if(this.currentRow==null){
                        this.$notify({
                                title: '校验失败',
                                message: '请选择父节点',
                                type: 'error',
                                duration: 2000
                            })
                            return
                    }
                    this.pageElementShow = true
                    this.temp.parentId = this.currentRow.id;
                    this.temp.parentMenuName = this.currentRow.menuName
                }
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            createData() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        create(this.temp).then(() => {
                            this.pageElementShow = false
                            this.dialogFormVisible = false
                            this.$notify({
                                title: '成功',
                                message: '创建成功',
                                type: 'success',
                                duration: 2000
                            })
                            this.getList()
                        })
                    }
                })
            },
            handleUpdate(row) {
                if(row.children ==null || row.children.length ==0){
                    this.pageElementShow = true
                }
                selectOne(row.id).then(response =>{
                    this.temp = response.data
                    this.dialogStatus = 'update'
                    this.dialogFormVisible = true
                    this.elementList = response.data.pageElement
                    this.$nextTick(() => {
                        this.$refs['dataForm'].clearValidate()
                    })
            }).catch(error =>{
                    this.$notify({
                        title: '失败',
                        message: error,
                        type: 'error',
                        duration: 2000
                    })
                })

            },
            updateData() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        const tempData = Object.assign({}, this.temp)
                        update(tempData).then(() => {
                        this.pageElementShow = false
                        this.dialogFormVisible = false
                        this.$notify({
                            title: '成功',
                            message: '更新成功',
                            type: 'success',
                            duration: 2000
                        })
                        this.getList()
                    })
                    }
                })
            },
            handleDelete(row, index) {
                MessageBox.confirm('是否确认删除', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(()=>{
                    del(row.id).then(response =>{
                        this.$notify({
                            title: '成功',
                            message: '删除成功',
                            type: 'success',
                            duration: 2000
                        })
                        this.getList()
                    }).catch(error =>{
                        this.$notify({
                            title: '删除失败',
                            message: error,
                            type: 'error',
                            duration: 2000
                        })
                    })
                })
            },
            handleCurrentChange(val) {
                this.currentRow = val;
            },
            openDialog(){
                if(this.elementList == null || this.elementList.length == 0){ 
                    const dicts = dictArray('PAGE_ELEMENTS')
                    if(dicts !=null && dicts.length>0){
                        this.elementList = []
                        dicts.forEach(element =>{
                            let ele = {
                                elementCode:element.dictCode,
                                elementName: element.dictValue
                            }
                            this.elementList.push(ele)
                        })
                    }
                }
            },
            addBtn(){
                let ele = {
                    elementCode:this.btn.elementCode,
                    elementName: this.btn.elementName
                }
                this.elementList.push(ele)
                this.innerVisible = false
            },
            closeDialog(){
                this.dialogFormVisible = false
                this.pageElementShow = false
            }
        }
    }
</script>
